package com.um.jdy.platform.sharing.manager;

import cn.hutool.core.util.StrUtil;
import com.github.binarywang.wxpay.bean.profitsharingV3.ProfitSharingReceiver;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.um.jdy.common.member.entity.po.MemberUser;
import com.um.jdy.common.member.service.MemberUserService;
import com.um.jdy.common.sharing.entity.po.Receiver;
import com.um.jdy.common.sharing.service.ReceiverService;
import com.um.jdy.common.commons.manager.WxManager;
import com.um.jdy.platform.sharing.entity.vo.SharingReceiverVO;
import com.um.springboot.starter.entity.Page;
import com.um.springboot.starter.orm.entity.Response;
import com.um.springboot.starter.orm.manager.BaseManager;
import com.um.springboot.starter.orm.params.PageParams;
import com.um.springboot.starter.properties.HshProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author 邓南辉
 * 日期 2023/5/11
 * 版权所有 广州优匠科技有限公司
 */
@Service
@Slf4j
public class SharingReceiverManager extends BaseManager<ReceiverService> {


    @Autowired
    WxManager wxManager;

    @Autowired
    WxPayService wxPayService;

    @Autowired
    MemberUserService memberUserService;

    @Autowired
    HshProperties hshProperties;

    public Response<Page<SharingReceiverVO>> getUserPage(PageParams params) {
        Page<SharingReceiverVO> page = new Page<>();
        page.setPageNo(params.getPageNo());
        page.setPageSize(params.getPageSize());
        params.getCondition().put("r.com_id", getComId());

        page = service.getCMSViewModelPageBySqlName(page, "get_sharing_receiver_page", "get_sharing_receiver_count", SharingReceiverVO.class, params.getProperties(), params.getValues(), params.getRangeEntitys(), params.getOrderNames(), params.getSortOns());

        return Response.success(page);
    }

    /**
     * 添加分账接收方
     *
     * @param userId
     * @return
     */
    @Transactional
    public Response addReceiver(String userId) {

        if(service.getEntity("member_user_id",userId) != null){
            return Response.failed("用户已存在，不能再添加");
        }

        MemberUser memberUser = memberUserService.getEntity(userId);
        if(memberUser == null){
            return Response.failed("用户不存在！");
        }

        String miniOpenId = memberUser.getMiniOpenId();
        if(miniOpenId == null){
            return Response.failed("用户未绑定小程序openid！");
        }


        wxManager.getPayService(getComId());

        ProfitSharingReceiver profitSharingReceiver = new ProfitSharingReceiver();
        profitSharingReceiver.setType(WxPayConstants.ReceiverType.PERSONAL_OPENID);
        profitSharingReceiver.setAccount(miniOpenId);
        profitSharingReceiver.setAppid(wxPayService.getConfig().getAppId());
        profitSharingReceiver.setRelationType("STORE_OWNER");

        try {
            wxPayService.getProfitSharingV3Service().addProfitSharingReceiver(profitSharingReceiver);
        } catch (WxPayException e) {
            log.error("添加分账接收方失败:{}", e);
            return Response.failed(StrUtil.format("添加分账接收方失败，{}", e.getCustomErrorMsg()));
        }

        Receiver sharingReceiver = new Receiver();
        sharingReceiver.setMemberUserId(userId);
        sharingReceiver.setCreateDate(new Date());
        sharingReceiver.setType(WxPayConstants.ReceiverType.PERSONAL_OPENID);
        sharingReceiver.setAccount(miniOpenId);
        service.add(sharingReceiver);

        return Response.success();
    }

    /**
     * 删除分账接收方
     *
     * @param sharingReceiverId
     * @return
     */
    @Transactional
    public Response removeReceiver(String sharingReceiverId) {
        Receiver entity = service.getEntity(sharingReceiverId);
        if(entity == null){
            return Response.failed("分账接收方不存在，删除失败！");
        }

        String account = entity.getAccount();
        String type = entity.getType();

        wxManager.getPayService(getComId());

        ProfitSharingReceiver profitSharingReceiver = new ProfitSharingReceiver();
        profitSharingReceiver.setType(type);
        profitSharingReceiver.setAccount(account);
        profitSharingReceiver.setAppid(wxPayService.getConfig().getAppId());

        try {
            wxPayService.getProfitSharingV3Service().deleteProfitSharingReceiver(profitSharingReceiver);
        } catch (WxPayException e) {
            log.error("删除分账接收方失败:{}",e);
            return Response.failed(StrUtil.format("删除分账接收方失败，{}", e.getCustomErrorMsg()));
        }

        service.delete(sharingReceiverId);

        return Response.success();
    }
}
